package websocketgulu.demo.controller;

import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import websocketgulu.demo.Utils.IdUtils;
import websocketgulu.demo.Utils.JsonResult;
import websocketgulu.demo.common.lang.Result;
import websocketgulu.demo.service.DoctorService;
import websocketgulu.demo.service.PatientService;

import java.util.HashMap;
import java.util.Map;

/**
 * @Classname:RegisterController
 * @author :liuao
 * @date：2021/5/19
 */
@RestController
public class RegisterController {
    @Autowired
    private DoctorService doctorService;
    @Autowired
    private PatientService patientService;


    @PostMapping("/register")
    public Result doctorRegister(@RequestParam Map<String, String> map) {
        System.out.println(map);
        System.out.println(map.get("name"));
        JsonResult jsonResult;
        // 判断是医生还是病人
        Integer identity = Integer.valueOf( map.get( "identity" ) );

        // 生成UUID
        map.put("id", IdUtils.getId());

        // 完成医生和病人的注册
        if( identity == 1 ){        // 医生
            return dRegister((HashMap) map);
        }else{
            return pRegister((HashMap) map);
        } // end if
    }


    /**
     * 完成病人注册的基本逻辑
     * @param map
     * @return
     */
    public Result pRegister( HashMap map ){
        //判断是否已经注册过了
        if(patientService.PT_is_exist((HashMap) map)){
            //创建json实体
            return Result.fail("用户已经注册过了");
        }else {
            patientService.addPatient((HashMap) map);
            return Result.success("注册成功");
        } // end if
    }


    /**
     * 完成医生注册的基本逻辑
     * @param map
     * @return
     */
    public Result dRegister( HashMap map ){
        // 判断是否已经注册过了
        if (doctorService.DC_is_exist( (HashMap) map ) ) {
            //创建json实体
            return Result.fail("用户已经注册过了");
            //return new JsonResult( false,  "用户已经注册过了");
        } else{
            // 查看医生的邀请码是否有效
            String code = (String) map.get( "invite_code" );
            if( ! doctorService.code_is_exist( code ) )
                return Result.fail("邀请码无效");

            // 将map插入到数据库中
            doctorService.addDoctor((HashMap) map );
            //创建json实体
            return Result.success("注册成功");
        } //end if

    }
}